<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<%@ include file="/common-css.jsp" %>
<%@ include file="/common-js.jsp" %>
<body>
<div class="layui-row">
	<div class="layui-col-md12">
		请选择对应的资源，点击“确定授权”进行保存
		<a class="layui-btn layui-btn-sm layui-btn-normal grantBtn">确定授权</a>
	</div> 
</div>
<div id="resourceTreeGrid" class="grid" ></div>
<input name="id" type="hidden"  value="${id}" >
<script id="resourceTreeGridView" type="text/html">
	<table class="layui-table">
		<thead>
			<tr>
                <th>资源名称  &nbsp;&nbsp;&nbsp;
				</th>
            </tr>
        </thead>
        <tbody>
            {{# layui.each(d.rows,function(index,r){ }}
            <tr>
                <td><input type="checkbox" name="resId" value="{{r.id}}" />{{r.name}}</td>
            </tr>
            {{# }); }}
        </tbody>
    </table>
</script>	
</body>
<script type="text/javascript">
layui.use(['laytpl','treegrid','jquery','form','layer'],function(){
	var laytpl = layui.laytpl;
	var treegrid = layui.treegrid;
	var $ = layui.jquery;
	var form = layui.form;
	var layer = parent.layer === undefined?layui.layer:parent.layer;
	
	treegrid.config.render = function(viewid,data){
		var view = document.getElementById(viewid).innerHTML;
        return laytpl(view).render(data) || '';
	};
	
	$.get('${pageContext.request.contextPath }/sys/sysResource/allResourceTree',function(ret){
		ret = $.parseJSON(ret);
		var rows = [];
		for(var i=0;i<ret.length;i++){
			var r = ret[i];
			rows.push({
				id:r.id,
				pid:r.pid==null?0:r.pid,
				title:r.name,
				name:r.name
			});
		}
		var tree1=treegrid.createNew({
	         elem: 'resourceTreeGrid',
	         view: 'resourceTreeGridView',
	         data: { rows: rows },
	         parentid: 'pid',
	         singleSelect: false
	     });
	     tree1.build();
	});
	
	//默认选中已授权的资源节点
	$.get('${pageContext.request.contextPath }/sys/sysRole/findResourceIdListByRoleId?id=${id}',function(ret){
		ret = $.parseJSON(ret);
		var rs = ret.obj;
// 		console.info(rs);
		var cb = $(":checkbox");
		for(var i=0;i<cb.length;i++){
			for(var j=0;j<rs.length;j++){
				if(cb[i].value == rs[i]){
					cb[i].checked = true;
				}
			}
		}
	});
	
	//确定授权按钮
	$(".grantBtn").click(function(){
		var reIds = '';
		$('input[name="resId"]:checked').each(function(){
				reIds += this.value+",";
		});
		if(reIds==''){
		}else{
			var id = $('input[name="id"]').val();
			var pli = progressLoad();
			$.post('${pageContext.request.contextPath }/sys/sysRole/grant',{id:id,resourceIds:reIds},function(ret){
				progressClose(pli);
				ret = $.parseJSON(ret);
				if(ret.success){
					layer.msg(ret.msg);
		 			layer.closeAll("iframe");
			 		//刷新父页面
			 		parent.location.reload();
				}else{
					layer.msg(ret.msg);
				}
			});
		}
	});
});
</script>
</html>